package cc.filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName: EncodingFilter
 * @Description: 字符集过滤器
 * @Author: 晓东√
 * @Date: 2024-09-04 10:11
 * @Version: 1.0
 **/
@WebFilter("*")
public class EncodingFilter extends HttpFilter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        request.setCharacterEncoding("utf-8");


        if (!request.getServletPath().toLowerCase().endsWith(".html")) {
            // 为html资源时，不再设置响应浏览器的编码
            response.setContentType("text/html;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
        }
        chain.doFilter(request, response);
    }
}
